﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Json;
using Hisuntech.SystemFramework.Net;
using WcfMail.Interface;
using Newtonsoft.Json;

namespace WcfMail.Common
{
    /// <summary>
    /// 对象、字符串转换类（工厂方法模式）
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract  class Converter
    {
        /// <summary>
        /// 采用默认的（JSON）序列化方式
        /// </summary>
        /// <returns></returns>
        public static IConvert CreateInstance()
        {
            return new NewTownJsonConvert();
        }


        public static IConvert CreateInstance(JsonSerializerType serType)
        {
            if (serType == JsonSerializerType.NewTownJson)
                return new NewTownJsonConvert();
            else
                return new WcfJsonConverter();
        }

        /// <summary>
        /// 采用指定的序列化方式
        /// </summary>
        /// <param name="serType"></param>
        /// <returns></returns>
        public static IConvert CreateInstance(SerializerType serType)
        {
            if (serType == SerializerType.JSON)
            {
                return new NewTownJsonConvert();
            }
            else if (serType == SerializerType.PdfNet)
            {
                return new PdfNetConvert();
            }
            throw new NotImplementedException("未实现当前类型的序列化方式：" + serType.ToString());
        }

        /// <summary>
        /// 转换成8位字符串,有利于将中文等非ASCII字符编码传输
        /// </summary>
        /// <param name="utf8String">UTF-8编码的字符串</param>
        /// <returns>8位编码的字符串</returns>
        public static string To8BitString(string utf8String)
        {
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(utf8String);
            return To8BitString(buffer );
        }

        /// <summary>
        /// 将字节数组编码为8位字符串
        /// </summary>
        /// <param name="buffer">字节数组</param>
        /// <returns>8位字符串</returns>
        public static string To8BitString(byte[] buffer)
        {
            Encoding _encoding = Encoding.GetEncoding(28591);
            string result = _encoding.GetString(buffer);
            return result;
        }

        /// <summary>
        /// 将8位字符串转换成UTF-8字符串
        /// </summary>
        /// <param name="bit8String">8位编码的字符串</param>
        /// <returns>UTF-8字符串</returns>
        public static string ToUtf8String(string bit8String)
        {
            Encoding _encoding = Encoding.GetEncoding(28591);
            byte[] buffer2 = _encoding.GetBytes(bit8String);
            string result2 = System.Text.Encoding.UTF8.GetString(buffer2);
            return result2;
        }
    }
}

